<template>
  <!-- 上传单张图片 -->
  <div v-if="!multiple" class="image-item">
    <div class="image-wrap" v-if="imgUrl">
      <img :src="imgUrl" :style="imgStyle" />
      <div class="icon-wrap"  @click.stop="removeFile">
        <i class="el-icon-delete"></i>
      </div>
    </div>
    <el-upload
      v-else
      ref="imageUpload"
      :action="oss.action"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      class="image-uploader"
      :on-error="onError"
      :data="oss"
      :show-file-list="false"
      :disabled="loading"
      accept="image/*"
    >
      <i :class="loading ? 'el-icon-loading' : 'el-icon-plus'" :style="imgStyle"></i>
    </el-upload>
  </div>
  <!-- 上传多张图片 -->
  <div class="image-list" v-else>
    <draggable v-model="showImgList" :options="{group:'image'}" @change="dragChange">
      <div v-for="(image, index) in showImgList" :key="index" class="image-wrap">
        <img :src="image" :style="imgStyle" />
        <div class="icon-wrap-zoom-in">
            <i class="el-icon-zoom-in" @click.stop="handlePreview(index)"></i>
        </div>
        <div class="icon-wrap">
          <i class="el-icon-caret-left" @click.stop="moveFile(index,-1)"></i>
        <i class="el-icon-delete" @click.stop="removeFile(index)"></i>
        <i class="el-icon-caret-right" @click.stop="moveFile(index,1)"></i>
        </div>
      </div>
      <el-upload
        ref="imageListUpload"
        :action="oss.action"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        class="image-uploader"
        :on-error="onError"
        :data="oss"
        multiple
        :disabled="loading"
        :show-file-list="false"
        accept="image/*"
      >
        <i :class="loading ? 'el-icon-loading' : 'el-icon-plus'" :style="imgStyle"></i>
      </el-upload>
    </draggable>
    <el-dialog :visible.sync="dialog.visible" :modal="false">
			<img width="100%" :src="dialog.imageUrl" alt="" />
		</el-dialog>
        
  </div>
</template>
<script type="text/babel">
/**
 * 上传图片或文件
 */
// import md5 from "blueimp-md5";
import draggable from "vuedraggable";

export default {
  props: {
    // 接收和返回的数据
    data: {
      type: [Array, String, Object],
      default: () => {
        return "";
      }
    },
    // 上传多个文件时，文件限制的个数
    limit: {
      type: Number,
      default: () => {
        return 100;
      }
    },
    // 一次上传多个
    multiple: {
      type: Boolean,
      default: false
    },
    //图片展示的宽度
    imgWidth: {
      type: Number,
      default: 150
    },
    imgHeight: {
      type: Number,
      default: 150
    },
    //期望上传图片的宽度
    rule: [Object, Function],
    dir: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      imgUrl: "",
      showImgList: [],
      fileList: [],
      clipboard: false,
      isDrag: false,
      handleSuccess: null,
      loading: false,
      oss: {
        policy: "",
        signature: "",
        key: "",
        OSSAccessKeyId: "",
        action: "",
        success_action_status: 200
      },
      dialog: { 
				visible: false, 
				imageUrl: '' ,
			},
    };
  },
  components: { draggable },
  watch: {
    data: {
      handler(value) {
        if (!this.multiple) {
          this.imgUrl = value;
        } else if (this.multiple) {
          this.showImgList = value;
        }
      },
      immediate: true
    }
  },
  computed: {
    imgStyle() {
      return {
        width: this.imgWidth + "px",
        height: this.imgHeight + "px",
        lineHeight: this.imgHeight + "px"
      };
    }
  },
  mounted() {
    //防抖
    // this.handleSuccess = debounce(this.uploadSuccess, 500);
    this.handleSuccess = this.uploadSuccess;
  },
  methods: {
    async beforeUpload(file) {
      if (file.type.split("/")[0] === "image") {
        let tempSize = file.size / 5242880;
        if (tempSize > 1) {
          this.$message.error("图片尺寸不得大于5M！");
          return false;
        }
      }
      let this_ = this;
      await this.$https
        .get("/file/getPolicyUploadInfo", { dir: this_.dir })
        .then(res => {
          let data = res.data.data;
          this_.oss.key = this_.dir + "/" + new Date().getTime() + file.name;
          this_.oss.policy = data.policy;
          this_.oss.OSSAccessKeyId = data.accessid;
          this_.oss.signature = data.signature;
          this_.oss.action = data.host;
        });
      this.loading = true;
    },
    async uploadSuccess(response, file, fileList) {
      try {
        let url = this.oss.action + '/' + this.oss.key;
        let imageInfo = await this.getImageInfo(url);
        this.showImgList.push(url);
        this.$emit("update:data", this.showImgList);
      } catch (error) {
        this.$message.error(error.message);
      } finally {
        this.loading = false;
        this.$refs.imageListUpload && this.$refs.imageListUpload.clearFiles();
        this.$refs.imageUpload && this.$refs.imageUpload.clearFiles();
      }
    },
    removeFile(index) {
      this.$confirm("确定删除该图片吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (this.type === "image") {
          this.$emit("update:data", typeof this.data === "object" ? {} : "");
        } else {
          this.showImgList.splice(index, 1);
          this.$emit("update:data", this.showImgList);
        }
      });
    },
    onError() {
      this.$message.error("上传文件失败");
    },
    getImageInfo(url) {
      return new Promise((resolve, reject) => {
        let image = new Image();
        image.src = url;
        // image.src = `${this.imageCdn}${url}`;
        image.onload = () => {
          resolve({
            image: url,
            width: image.width,
            height: image.height
          });
        };
        image.onerror = () => {
          reject(new Error("Could not load image at " + url));
        };
      });
    },
    dragChange() {
      this.$emit("update:data", this.showImgList);
    },
    moveFile(index,type) {
        let newIndex=index+type;
        if(newIndex>=this.showImgList.length || newIndex<0) {
            return;
        }
        this.showImgList[index] = this.showImgList.splice(newIndex, 1, this.showImgList[index])[0];
        this.$emit("update:data", this.showImgList);
    },
    handlePreview(index) {
        this.dialog = {
				visible: true,
				imageUrl: this.showImgList[index]
			};
    }
  }
};
</script>
<style lang="less" scoped>
.image-list,
.image-item {
  display: flex;
  .image-wrap {
    position: relative;
    display: inline-block;
    box-sizing: content-box;
    margin: 0 8px 8px 0;
    vertical-align: top;
    &:hover {
      .icon-wrap {
        opacity: 1;
      }
      .icon-wrap-zoom-in {
        opacity: 1;
      }
    }
    .icon-wrap-zoom-in {
        left: 0;
        top: 0;
        width: 100%;
        height: 70%;
        position: absolute;
        text-align: center;
        cursor: default;
        opacity: 0;
        background-color: rgba(0, 0, 0, 0.7);
        transition: opacity 0.3s;
        font-size: 25px;
        .el-icon-zoom-in {
        cursor: pointer;
        top: 50%;
        position: relative;
      }
    }
    
    .icon-wrap {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 30%;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, 0.7);
      transition: opacity 0.3s;
      .el-icon-delete {
        cursor: pointer;
      }
      .el-icon-caret-left {
        cursor: pointer;
        margin-right: 10px;
      }
      .el-icon-caret-right {
        cursor: pointer;
        margin-left: 10px;
      }
    }
  }
}
.image-item {
  display: inline-flex;
}
/deep/.image-uploader {
  display: inline-block;
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    [class^="el-icon"] {
      font-size: 28px;
      color: #8c939d;
      text-align: center;
    }
    &:hover {
      border-color: #409eff;
    }
  }
}
</style>